package com.huawei.esdk.oa.device.exchange;

import java.util.List;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.bean.aa.AccountInfo;
import com.huawei.esdk.platform.common.bean.config.DeviceConfig;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.platform.nemgr.base.MultiConnDeviceBase;
import com.huawei.esdk.platform.nemgr.itf.IDeviceConnection;
import com.huawei.esdk.platform.nemgr.itf.IDeviceManager;
import com.huawei.esdk.tp.device.oa.IExchangeCapability;

public class ExchangeDevice extends MultiConnDeviceBase {
	
	private static final Logger LOGGER = Logger
			.getLogger(ExchangeDevice.class);
	
    private IDeviceManager deviceManager = ApplicationContextUtil
            .getBean("deviceManager");
	
    private String sap;
    
	public ExchangeDevice(String sap) {
        this.sap = sap;
        prepareDeviceCapability(sap);
	}
	
	private void prepareDeviceCapability(String sap)
	{
        LOGGER.debug("The SAP = " + sap);
        addServiceObjectMap(IExchangeCapability.class, new ExchangeCapability());
	}

	@Override
	public IDeviceConnection createConnection(String connId, String sap,
			String loginUser, String loginPwd) {
		
		AccountInfo accountInfo = authorizePolicy.getDeviceAccountInfo(loginUser, loginPwd);
		DeviceConfig device = getDeviceInfo(accountInfo.getDevId());
		String version = null;
		String name = null;
		if(null != device)
		{
			version = device.getDeviceVersion();
			name = device.getDeviceName();
		}
		return new ExchangeConnection(this, sap, loginUser, loginPwd, version, name);
	}

	@Override
	public String getConnIdFromContext() {
		return "";
	}

	@Override
	public Boolean releaseConns() {
        for (String key : id2Connection.keySet())
        {
            IDeviceConnection conn = id2Connection.get(key);
            deviceManager.releaseConn(conn);
        }
        return true;
	}

    private DeviceConfig getDeviceInfo(String devId)
    {
        List<DeviceConfig> devices = deviceManager.queryAllDeviceInfo();
        if (null != devices)
        {
            for (DeviceConfig device : devices)
            {
                if (null != device && null != device.getDeviceId() && devId.equals(device.getDeviceId().trim()))
                {
                    return device;
                }
            }
        }
        
        return null;
    }
    
	public String getSap() {
		return sap;
	}

	public void setSap(String sap) {
		this.sap = sap;
	}
	
}